import java.util.Arrays;

/*
三路快速排序 O(NlogN)
*/
public class QuickSort {
    public static void main(String[] args) {
//        partition();
        quickSort();
    }

    private static void quickSort() {
        int[] arr = {1, 2, 5, 4, 7, 3, 8, 9, 0, 2, 3, 4, 7, 2, 4, 3, 6, 8, 7};
        sort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    private static void sort(int[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        int v = arr[l]; //先让l对应的元素与后面的随机交换 再使用l对应的数据
        int lt = l;
        int gt = r + 1;
        int i = l + 1;
        while (i < gt) {
            if (arr[i] < v) {
                swap(arr, lt + 1, i);
                i++;
                lt++;
            } else if (arr[i] > v) {
                swap(arr, gt - 1, i);
                gt--;
            } else {
                i++;
            }
        }
        swap(arr, l, lt);
        sort(arr, l, lt - 1);
        sort(arr, gt, r);
    }

    private static void partition() {
        int[] arr = {4, 1, 2, 3, 4, 5, 6, 7, 3, 2, 5, 6, 7, 8, 3, 4, 2, 4};
        int v = arr[0];
        int l = 0;
        int r = arr.length - 1;
        int lt = l;
        int gt = r + 1;
        int i = l + 1;
        while (i < gt) {
            if (arr[i] < v) {
                swap(arr, lt + 1, i);
                i++;
                lt++;
            } else if (arr[i] > v) {
                swap(arr, gt - 1, i);
                gt--;
            } else {
                i++;
            }
        }
        swap(arr, l, lt);
        System.out.println(Arrays.toString(arr));
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}




